<template>
  <div v-if="show">
    <el-dialog
      :title="title"
      :model-value="show"
      width="800"
      class="comDialog"
      :before-close="cancel"
      @opened="openCallBack"
    >
      <el-collapse :model-value="activeStatus">
        <!-- 投诉受理 -->
        <el-collapse-item :name="1">
          <template #title>
            <title-name
              title="投诉受理"
              icon="i-carbon-bookmark-filled"
            ></title-name>
          </template>
          <el-form
            :model="form"
            label-width="120px"
            :rules="formRules"
            ref="formRefs"
          >
            <el-row>
              <el-col :span="10">
                <el-form-item label="投诉来源" prop="complaintSource">
                  <el-radio-group
                    v-model="form.complaintSource"
                    :disabled="dialogType !== 'add'"
                  >
                    <el-radio label="1">顾客</el-radio>
                    <el-radio label="2">第三方</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="投诉单位" prop="complaintOrg">
                  <el-input
                    v-model="form.complaintOrg"
                    :disabled="dialogType !== 'add'"
                    placeholder="请输入投诉单位"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="投诉人" prop="complaintPerson">
                  <el-input
                    v-model="form.complaintPerson"
                    :disabled="dialogType !== 'add'"
                    placeholder="请输入投诉人"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="联系电话" prop="contactNumber">
                  <el-input
                    v-model="form.contactNumber"
                    :disabled="dialogType !== 'add'"
                    placeholder="请输入联系电话"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="被诉单位" prop="beComplaintOrg">
                  <el-select
                    v-model="form.beComplaintOrg"
                    placeholder="请选择被诉单位"
                    clearable
                    :disabled="dialogType !== 'add'"
                    @change="handleBeComplaintOrgChange"
                  >
                    <el-option
                      v-for="(item, index) in orgOptions"
                      :value="item.value"
                      :label="item.label"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="被诉部门" prop="beComplaintDept">
                  <el-select
                    v-model="form.beComplaintDept"
                    placeholder="请选择被诉部门"
                    clearable
                    :disabled="dialogType !== 'add'"
                    @focus="checkSelect"
                  >
                    <el-option
                      v-for="(item, index) in deptOptions"
                      :value="item.value"
                      :label="item.label"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="被诉人" prop="beComplaintPerson">
                  <el-select
                    v-model="form.beComplaintPerson"
                    @focus="activeSelectDialog"
                    ref="selectFocus"
                    :disabled="dialogType !== 'add'"
                    placeholder="请选择被诉人"
                  >
                    <el-option
                      v-for="(item, index) in selectOptions"
                      :value="item.value"
                      :label="item.label"
                      :key="index"
                    ></el-option
                  ></el-select>
                </el-form-item>
              </el-col>
              <el-col :span="10" v-if="isShowForm(status, 1)">
                <el-form-item label="编号">
                  <el-input disabled v-model="form.no"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="投诉内容" prop="content">
                  <el-input
                    type="textarea"
                    v-model="form.content"
                    resize="none"
                    rows="5"
                    show-word-limit
                    :maxlength="250"
                    :disabled="dialogType !== 'add'"
                    placeholder="请输入投诉内容"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="顾客诉求" prop="customerAppeal">
                  <el-input
                    type="textarea"
                    v-model="form.customerAppeal"
                    resize="none"
                    rows="5"
                    :disabled="dialogType !== 'add'"
                    placeholder="请输入顾客诉求"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isShowForm(status, 1)">
              <el-col :span="10">
                <el-form-item label="受理人">
                  <el-input
                    v-model="form.createBy"
                    disabled
                  ></el-input></el-form-item
              ></el-col>
              <el-col :span="10"
                ><el-form-item label="受理日期">
                  <el-input
                    v-model="form.createTime"
                    disabled
                  ></el-input></el-form-item
              ></el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
        <!-- 投诉核实 -->
        <el-collapse-item :name="2" v-if="isShowForm(status, 0)">
          <template #title>
            <title-name
              title="投诉核实"
              icon="i-carbon-bookmark-filled"
            ></title-name>
          </template>
          <el-form
            :model="verifyForm"
            label-width="120px"
            :rules="verifyFormRules"
            ref="verifyFormRef"
          >
            <el-row>
              <el-col :span="20">
                <el-form-item label="核实内容" prop="content">
                  <el-input
                    type="textarea"
                    v-model="verifyForm.content"
                    resize="none"
                    show-word-limit
                    :maxlength="250"
                    rows="5"
                    :disabled="isShowForm(status, 1, false)"
                    placeholder="请输入核实内容"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isShowForm(status, 1, false)">
              <el-col :span="10">
                <el-form-item disabled label="核实人" prop="createBy">
                  <el-input v-model="verifyForm.createBy" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item disabled label="核实日期" prop="createTime">
                  <el-input v-model="verifyForm.createTime" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
        <!-- 投诉处理 -->
        <el-collapse-item :name="3" v-if="isShowForm(status, 1)">
          <template #title>
            <title-name
              title="投诉处理"
              icon="i-carbon-bookmark-filled"
            ></title-name>
          </template>
          <el-form
            :model="optionInputForm"
            label-width="120px"
            :rules="optionInputFormRules"
            ref="optionInputFormRef"
          >
            <el-row>
              <el-col :span="20">
                <el-form-item label="处理意见" prop="content">
                  <el-input
                    type="textarea"
                    v-model="optionInputForm.content"
                    resize="none"
                    rows="5"
                    show-word-limit
                    :maxlength="250"
                    :disabled="isShowForm(status, 2, false)"
                    placeholder="请输入处理意见"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isShowForm(status, 2, false)">
              <el-col :span="10">
                <el-form-item label="处理人">
                  <el-input
                    v-model="optionInputForm.createBy"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="处理日期">
                  <el-input
                    v-model="optionInputForm.createTime"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-form
            :model="dealWithForm"
            label-width="120px"
            :rules="dealWithFormRules"
            ref="dealWithFormRef"
          >
            <el-row v-if="isShowForm(status, 2)">
              <el-col :span="20">
                <el-form-item label="处理结果" prop="content">
                  <el-input
                    type="textarea"
                    v-model="dealWithForm.content"
                    resize="none"
                    rows="5"
                    show-word-limit
                    :maxlength="250"
                    :disabled="isShowForm(status, 3, false)"
                    placeholder="请输入处理结果"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="20">
                <el-form-item label="附件:" prop="附件">
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :http-request="handleFileChange"
                    accept=".rar, .zip, .doc, .docx, .pdf"
                    :show-file-list="false"
                    :multiple="true"
                  >
                    <template #tip>
                      <div class="text-14px color-#999">
                        支持类型:rar, zip, doc, docx, pdf,文件大小限制20MB内
                      </div>
                    </template>
                    <el-button
                      type="primary"
                      :disabled="isShowForm(status, 3, false)"
                      style="font-size: 14px"
                      ><el-icon> <UploadFilled /> </el-icon>上传附件</el-button
                    >
                  </el-upload>
                  <div class="text-14px" style="width: 100%">
                    <div v-for="(item, index) in fileList" :key="item.fileId">
                      <a style="color: #409eff" :href="item.url">{{
                        item.origFileName
                      }}</a>
                      <el-button
                        text
                        plain
                        @click="delFileName(index)"
                        v-if="!isShowForm(status, 3, false)"
                        >删除</el-button
                      >
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isShowForm(status, 3)">
              <el-col :span="10">
                <el-form-item disabled label="处理人">
                  <el-input v-model="dealWithForm.createBy" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item disabled label="处理日期">
                  <el-input
                    v-model="dealWithForm.createTime"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
        <!-- 投诉确认 -->
        <el-collapse-item :name="4" v-if="isShowForm(status, 3)">
          <template #title>
            <title-name
              title="投诉确认"
              icon="i-carbon-bookmark-filled"
            ></title-name>
          </template>
          <el-form
            :model="confirmForm"
            label-width="120px"
            :rules="confirmFormRules"
            ref="confirmFormRef"
          >
            <el-row>
              <el-col :span="10">
                <el-form-item label="投诉判定" prop="judge">
                  <el-radio-group
                    v-model="confirmForm.judge"
                    :disabled="isShowForm(status, 4, false)"
                  >
                    <el-radio label="1">有效投诉</el-radio>
                    <el-radio label="0">无效投诉</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="判定关键点" prop="content">
                  <el-input
                    type="textarea"
                    v-model="confirmForm.content"
                    resize="none"
                    rows="5"
                    :disabled="isShowForm(status, 4, false)"
                    placeholder="请输入判定关键点"
                    show-word-limit
                    :maxlength="250"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="20">
                <el-form-item label="回访情况" prop="content2">
                  <el-input
                    type="textarea"
                    v-model="confirmForm.content2"
                    resize="none"
                    rows="5"
                    show-word-limit
                    :maxlength="250"
                    :disabled="isShowForm(status, 4, false)"
                    placeholder="请输入回访情况"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isShowForm(status, 4, false)">
              <el-col :span="10">
                <el-form-item disabled label="负责人">
                  <el-input v-model="confirmForm.createBy" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item disabled label="处理日期">
                  <el-input
                    v-model="confirmForm.createTime"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-collapse-item>
      </el-collapse>

      <template #footer>
        <el-button @click="cancel" v-if="dialogType !== 'details'"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="confirm"
          v-if="dialogType !== 'details'"
          >确认</el-button
        >
        <el-button v-if="dialogType === 'details'" @click="cancel"
          >关闭</el-button
        >
      </template></el-dialog
    >
    <SelectDialog
      :dialog-param="dialogParam"
      @ok="selectData"
      @close="closeFn"
    />
  </div>
</template>

<script setup>
import useUserStore from '@/store/modules/user'
import { getUser } from '@/api/system/user'
import { editComplaint } from '@/api/ord'
import { validatePhone } from '@/utils/validate'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import { treeselectNoPriv } from '@/api/rsgl/zzjg'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  show: {
    type: Boolean,
    default: false
  },
  dialogType: {
    type: String,
    default: 'add'
  },
  complaintDetail: {
    type: Object,
    default: () => {}
  },
  status: {
    type: String,
    default: '1'
  }
})

const orgOptions = ref([])
const deptOptions = ref([])
function getInitData() {
  treeselectNoPriv({ parentId: 100 }).then(res => {
    orgOptions.value = res.data.map(v => ({
      value: v.id,
      label: v.label
    }))
  })
}

function handleBeComplaintOrgChange(val) {
  form.value.beComplaintDept = ''
  deptOptions.value = []
  if (val) {
    treeselectNoPriv({ parentId: val }).then(res => {
      deptOptions.value = res.data.map(v => ({
        value: v.id,
        label: v.label
      }))
    })
  }
}
function checkSelect() {
  if (!form.value.beComplaintOrg) {
    proxy.$modal.msgWarning('请先选择被诉单位')
  }
}
const isShowForm = computed(
  (status, num, show = true) =>
    (status, num, show = true) => {
      let result
      if (props.dialogType === 'details') {
        result = status - 1 > num

        if (!show) {
          result = true
        }
      } else {
        result = status > num
      }
      return result
    }
)
// 录入表单
const form = ref({})
const formRules = ref({
  complaintSource: [
    { required: true, message: '请选择投诉来源', trigger: 'change' }
  ],
  complaintOrg: [
    { required: true, message: '请输入投诉单位', trigger: 'change' }
  ],
  complaintPerson: [
    { required: true, message: '请输入投诉人', trigger: 'change' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'change' },
    {
      validator: validatePhone,
      message: '请输入正确的电话号码',
      trigger: 'change'
    }
  ],
  // beComplaintOrg: [
  //   { required: true, message: '请输入被诉单位', trigger: 'change' }
  // ],
  // beComplaintDept: [
  //   { required: true, message: '请输入被诉部门', trigger: 'change' }
  // ],
  // beComplaintPerson: [
  //   { required: true, message: '请选择被诉人', trigger: 'change' }
  // ],
  content: [{ required: true, message: '请输入投诉内容', trigger: 'change' }],
  customerAppeal: [
    { required: true, message: '请输入顾客诉求', trigger: 'change' }
  ]
})
// 核实表单
const verifyForm = ref({})
const verifyFormRules = ref({
  content: [{ required: true, message: '请输入核实内容', trigger: 'change' }]
})
// 录入意见表单
const optionInputForm = ref({})
const optionInputFormRules = ref({
  content: [{ required: true, message: '请输入录入意见', trigger: 'change' }]
})
// 处理表单
const dealWithForm = ref({})
const dealWithFormRules = ref({
  content: [{ required: true, message: '请输入处理意见', trigger: 'change' }]
})

// 确认表单
const confirmForm = ref({})
const confirmFormRules = ref({
  judge: [{ required: true, message: '请选择投诉判定', trigger: 'change' }],
  content: [{ required: true, message: '请输入判定关键点', trigger: 'change' }],
  content2: [{ required: true, message: '请输入回访情况', trigger: 'change' }]
})

const emit = defineEmits(['update:show', 'getList'])

function confirm() {
  if (props.dialogType === 'add') {
    // 新增
    proxy.$refs.formRefs.validate(valid => {
      if (valid) {
        const params = { ...form.value }
        editComplaint(params).then(res => {
          proxy.$modal.msgSuccess('新增成功')
          cancel()
          emit('getList')
        })
      }
    })
  } else {
    // 编辑
    let refs, params, msg
    switch (Number(props.status)) {
      case 1:
        // 核实
        refs = 'verifyFormRef'
        msg = '核实成功'
        params = {
          list: [{ ...verifyForm.value, stage: Number(props.status) + 1 }],
          id: props.complaintDetail.id
        }
        break
      case 2:
        // 录入意见
        refs = 'optionInputFormRef'
        msg = '录入意见成功'
        params = {
          list: [{ ...optionInputForm.value, stage: Number(props.status) + 1 }],
          id: props.complaintDetail.id
        }
        break
      case 3:
        // 处理
        if (fileList.value && fileList.value.length) {
          dealWithForm.value.fileNames = fileList.value.map(v => v.fileName)
        }

        refs = 'dealWithFormRef'
        msg = '处理成功'
        params = {
          list: [{ ...dealWithForm.value, stage: Number(props.status) + 1 }],
          id: props.complaintDetail.id
        }
        break
      case 4:
        // 确认
        refs = 'confirmFormRef'
        msg = '确认成功'
        params = {
          list: [{ ...confirmForm.value, stage: Number(props.status) + 1 }],
          id: props.complaintDetail.id
        }
        break
    }
    formSubmitHangel(refs, params, msg)
  }
}

// 表单验证
function formSubmitHangel(refs, params, msg) {
  proxy.$refs[refs].validate(valid => {
    if (valid) {
      submitRequest(params, msg)
    }
  })
}

// 处理接口
function submitRequest(params, msg) {
  if (params.list[0].id) {
    delete params.list[0].id
  }
  editComplaint(params).then(res => {
    proxy.$modal.msgSuccess(msg)
    emit('getList')
    cancel()
  })
}
function cancel() {
  form.value = {}
  verifyForm.value = {}
  optionInputForm.value = {}
  dealWithForm.value = {}
  confirmForm.value = {}
  fileList.value = []
  emit('update:show', false)
}

// 打开回调
const activeStatus = ref()
function openCallBack() {
  getInitData()
  activeStatus.value = [1, 2, 3, 4, 5]
  dialogParam.value = {
    type: 'Sued',
    isDialog: false,
    title: '选择被诉人',
    dataType: 'person',
    nodeKey: 'uuid',
    // multiple: true,
    checkStrictly: false,
    apiParams: { deptId: 100 },
    defaultCheckedKeys: []
  }
  if (props.dialogType !== 'details') {
    proxy.$nextTick(() => {
      const timer = setTimeout(() => {
        const scrollTag = document.querySelector('.comDialog .el-dialog__body')
        const height = scrollTag.scrollHeight
        scrollTag.scrollTo({
          top: height,
          behavior: 'smooth'
        })
        clearTimeout(timer)
      }, 500)
    })
  }
}

// 选择被诉人
const dialogParam = ref({
  type: 'Sued',
  isDialog: false,
  title: '选择被诉人',
  dataType: 'person',
  nodeKey: 'uuid',
  // multiple: true,
  checkStrictly: false,
  apiParams: { deptId: 100 },
  defaultCheckedKeys: []
})
const selectOptions = ref([])
function selectData(val) {
  selectOptions.value =
    val.selectData.map(v => ({
      value: v.uuid.replace('U', ''),
      label: v.label
    })) || []
  dialogParam.value.defaultCheckedKeys = val.defaultCheckedKeys
  form.value.beComplaintPerson = selectOptions.value[0]?.value || ''
}

function activeSelectDialog() {
  dialogParam.value.isDialog = true
  proxy.$refs.selectFocus.blur()
}
function closeFn() {
  dialogParam.value.isDialog = false
}

// 文件上传

const fileList = ref([])
// 上传方法
async function handleFileChange(params) {
  const type = params.file.name.substring(params.file.name.lastIndexOf('.'))
  const allowType = ['.rar', '.zip', '.doc', '.docx', '.pdf'].indexOf(type) < 0
  if (allowType) {
    proxy.$message.error('上传文件只能是rar、zip、doc、docx、pdf格式!')
    return false
  }
  if (params.file.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
      dealWithForm.value.file
    }
  } catch (error) {
    console.error(error)
  }
}

// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
  }
}

watch(
  () => props.complaintDetail,
  val => {
    form.value = val
    if (props.dialogType !== 'add') {
      form.value.beComplaintDept = val.beComplaintDeptCn
      form.value.beComplaintOrg = val.beComplaintOrgCn
      if (val.list && val.list.length) {
        verifyForm.value = val.list[0] || {}
        optionInputForm.value = val.list[1] || {}
        dealWithForm.value = val.list[2] || {}
        confirmForm.value = val.list[3] || {}
        fileList.value = val.list[2]?.sysAttachFiles || []
      }
      selectOptions.value = [
        {
          value: val.beComplaintPerson,
          label: val.beComplaintPersonCn
        }
      ]
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss"></style>
